package cn.dankal.flyaudio.personal;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;

import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.lifecycle.Observer;
import api.UserServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.DankalApplication;
import cn.dankal.basiclib.GlideApp;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.camera.CameraHandlerTow;
import cn.dankal.basiclib.common.qiniu.UploadListener;
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer;
import cn.dankal.basiclib.common.upload.ali.AliUploadHelper;
import cn.dankal.basiclib.pojo.UserInfoBean;
import cn.dankal.basiclib.protocol.LoginProtocol;
import cn.dankal.basiclib.rx.AbstractDialogSubscriber;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.template.personal.ChangeAvatar;
import cn.dankal.basiclib.template.personal.ChangeAvatarImpl;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.JMessageToastUtils;
import cn.dankal.basiclib.util.StringUtil;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.util.UriUtils;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.basiclib.widget.ChoiceAddressCityDialog;
import cn.dankal.basiclib.widget.TipDialog;
import cn.dankal.business.eventbus.MessageUpdatePersonEvent;
import cn.dankal.business.pojo.ReasonBean;
import cn.dankal.flyaudio.R;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;

public class PersonalBaseProfileActivity extends BaseActivity implements View.OnClickListener {

    private static final int SETNAME_REQUESTCODE = 205;

    private static final int SET_NICK_NAME = 2002;

    private ImageView avatarView;

    private TextView nickNameView;

    private TextView phoneView;

    private TextView emailView;

    private TextView genderBoyView;

    private TextView genderGirlView;

    private TextView addressView;
    private TextView tvInterast;


    private ChangeAvatar changeAvatar;
    private UploadListener uploadListener;
    private AliUploadHelper uploadHelper;
    private TipDialog.Builder builder;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_personal_base_profile;
    }

    @Override
    protected void initComponents() {
        avatarView = findViewById(R.id.iv_avatar);
        nickNameView = findViewById(R.id.tv_nickname);
        phoneView = findViewById(R.id.et_phone);
        emailView = findViewById(R.id.et_email);
        genderBoyView = findViewById(R.id.tv_gender_boy);
        genderGirlView = findViewById(R.id.tv_gender_girl);
        addressView = findViewById(R.id.tv_address);
        tvInterast = findViewById(R.id.tv_interast);
        avatarView.setOnClickListener(this);
        findViewById(R.id.cl_my_address).setOnClickListener(this);
        findViewById(R.id.cl_interast).setOnClickListener(this);
        findViewById(R.id.cl_update_password).setOnClickListener(this);
        findViewById(R.id.cl_my_mobile).setOnClickListener(this);
        findViewById(R.id.tv_save).setOnClickListener(this);
        genderBoyView.setOnClickListener(this);
        findViewById(R.id.cl_address).setOnClickListener(this);
        genderGirlView.setOnClickListener(this);
        findViewById(R.id.cl_my_email).setOnClickListener(this);
        findViewById(R.id.cl_update_nickname).setOnClickListener(this);
        UserInfoBean userInfo = DKUserManager.getUserInfo();
        nickNameView.setText(userInfo.getName());
        phoneView.setText(userInfo.getPhone());
        addressView.setText(userInfo.getCarCity());
        if(!StringUtils.isEmpty(userInfo.getInterest())){
            StringBuilder sb = new StringBuilder();
            List<String> intersets = JSON.parseArray(userInfo.getInterest(),String.class);

            for (String str : intersets) {
                sb.append(str);
                sb.append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            tvInterast.setText(sb.toString());
        }else {
            tvInterast.setText("");
        }
        if (StringUtils.equals(genderBoyView.getText(), userInfo.getSex())) {
            genderBoyView.setSelected(true);
        }
        if (StringUtils.equals(genderGirlView.getText(), userInfo.getSex())) {
            genderGirlView.setSelected(true);
        }
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        LiveEventBus.get("update_user_info", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                UserInfoBean userInfo = DKUserManager.getUserInfo();
                nickNameView.setText(userInfo.getName());
                phoneView.setText(userInfo.getPhone());
                emailView.setText(userInfo.getEmail());
                if(!StringUtils.isEmpty(userInfo.getInterest())){
                    StringBuilder sb = new StringBuilder();
                    List<String> intersets = JSON.parseArray(userInfo.getInterest(),String.class);

                    for (String str : intersets) {
                        sb.append(str);
                        sb.append(",");
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    tvInterast.setText(sb.toString());
                }else {
                    tvInterast.setText("");
                }
            }
        });
        emailView.setText(userInfo.getEmail());
        PicUtils.loadAvatar(userInfo.getAvatar(), avatarView);
        changeAvatar = new ChangeAvatarImpl(this, this);
        changeAvatar.setIvHead(avatarView);
        uploadListener = new UploadListener() {
            @Override
            public void onSucess(String filepath, String key) {
                loadingDialog.dismiss();

                UserServiceFactory.changeAvatar(key)
                        .subscribe(new AbstractSubscriber<ReasonBean>(PersonalBaseProfileActivity.this) {
                            @Override
                            public void onNext(ReasonBean reasonBean) {
                                LiveEventBus.get("update_user_info", String.class).post("");
                            }
                        });
                JMessageClient.updateUserAvatar(file, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        JMessageToastUtils.errorToast(i);
                    }
                });
            }

            @Override
            public void onUpload(double percent) {
                builder.setTipWord(percent + "%").showProgress();
            }

            @Override
            public void onError(String string) {
                ToastUtils.showLong(string);
                loadingDialog.dismiss();
                TipDialog dialog = builder.setIconType(TipDialog.Builder.ICON_TYPE_FAIL)
                        .setTipWord("上传失败")
                        .create(2000);
                dialog.show();
                dialog.dismiss();
            }
        };
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SETNAME_REQUESTCODE) {
//            nickNameView.setText(data.getStringExtra("编辑昵称"));
            return;
        }
        // 图片、视频、音频选择结果回调
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        // 例如 LocalMedia 里面返回三种path
        // 1.media.getPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
        if (selectList != null && selectList.size() > 0) {
            setImage(selectList);
        }
    }

    private File file;

    private void setImage(List<LocalMedia> list) {
        LocalMedia media = list.get(0);
        String mimeType = media.getMimeType();
        String path = "";
        if (media.isCut() && !media.isCompressed()) {
            // 裁剪过
            path = media.getCutPath();
        } else if (media.isCompressed() || media.isCut() && media.isCompressed()) {
            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
            path = media.getCompressPath();
        } else {
            // 原图
            path = media.getPath();
        }
        // 图片
        if (media.isCompressed()) {
            Log.i("compress image result:", (new File(media.getCompressPath()).length() / 1024) + "k");
            Log.i("压缩地址::", media.getCompressPath());
        }

        Log.i("原图地址::", media.getPath());
        //int pictureType = PictureMimeType.isPictureType(media.getPictureType());
        if (media.isCut()) {
            Log.i("裁剪地址::", media.getCutPath());
        }
        try {
            //uploadImage = UIUtils.compressImage(UIUtils.getBitmapFromUrl(path, 200, 200))
            Uri uri = Uri.parse(path);
            file = new File(path);
            GlideApp.with(DankalApplication.getContext()).asBitmap().centerCrop().error(R.mipmap.pic_ill_4).load(path).into(new BitmapImageViewTarget(avatarView) {
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    avatarView.setImageDrawable(circularBitmapDrawable);
                }
            });
            //Glide.with(this).load(path).into(iv_head)
            MessageUpdatePersonEvent event = new MessageUpdatePersonEvent(uri);
            event.setPath(path);
            EventBus.getDefault().post(event);
            uploadPic(uri);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void uploadPic(Uri photoUris) {
        builder = new TipDialog.Builder(this);
        loadingDialog = builder
                .setIconType(TipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在上传").create();
        loadingDialog.show();
        boolean b = UriUtils.getPath(this, photoUris) == null;
        uploadHelper.uploadPic(uploadListener, b ? photoUris.getPath() : UriUtils.getPath(this, photoUris));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_save:
                ToastUtils.showShort("修改成功");
                finish();
                break;
            case R.id.cl_interast:
                ActivityUtils.startActivity(SetInterastActivity.class);
                break;
            case R.id.tv_gender_boy:
                genderGirlView.setSelected(false);
                genderBoyView.setSelected(true);
                UserServiceFactory.changeSex(genderBoyView.getText().toString())
                        .subscribe(new AbstractDialogSubscriber<ReasonBean>(PersonalBaseProfileActivity.this) {
                            @Override
                            public void onNext(ReasonBean reasonBean) {
                                UserInfoBean userInfoBean = DKUserManager.getUserInfo();
                                userInfoBean.setSex(genderBoyView.getText().toString());
                                DKUserManager.updateUserInfo(userInfoBean);
                                LiveEventBus.get("update_user_info", String.class).post("");
                            }
                        });
                break;
            case R.id.tv_gender_girl:
                genderGirlView.setSelected(true);
                genderBoyView.setSelected(false);
                UserServiceFactory.changeSex(genderGirlView.getText().toString())
                        .subscribe(new AbstractDialogSubscriber<ReasonBean>(PersonalBaseProfileActivity.this) {
                            @Override
                            public void onNext(ReasonBean reasonBean) {
                                UserInfoBean userInfoBean = DKUserManager.getUserInfo();
                                userInfoBean.setSex(genderGirlView.getText().toString());
                                DKUserManager.updateUserInfo(userInfoBean);
                                LiveEventBus.get("update_user_info", String.class).post("");
                            }
                        });
                break;
            case R.id.cl_address:
                ChoiceAddressCityDialog dialog = new ChoiceAddressCityDialog(this, new ChoiceAddressCityDialog.OnConfirmAddressListener() {
                    @Override
                    public void onConfirm(String curProvice, String curCity) {
                        Map<String, Object> params = new HashMap<>();
                        params.put("carCity", curCity);
                        params.put("carProvince", curProvice);
                        UserServiceFactory.changeCity(params)
                                .subscribe(new AbstractDialogSubscriber<ReasonBean>(PersonalBaseProfileActivity.this) {
                                    @Override
                                    public void onNext(ReasonBean reasonBean) {
                                        UserInfoBean userInfoBean = DKUserManager.getUserInfo();
                                        userInfoBean.setCarCity(curCity);
                                        DKUserManager.updateUserInfo(userInfoBean);
                                        addressView.setText(userInfoBean.getCarCity());
                                        LiveEventBus.get("update_user_info", String.class).post("");
                                    }
                                });
                    }
                });
                dialog.show();
                break;
            case R.id.cl_update_nickname:
                startActivityForResult(new Intent(this, SettingNickNameActivity.class), SETNAME_REQUESTCODE);
                break;
            case R.id.cl_my_address:
                ActivityUtils.startActivity(AddressManagerActivity.class);
                break;
            case R.id.cl_my_email:
                EventBus.getDefault().post(new MessageUpdatePersonEvent(null));
                Intent intent = new Intent(this, EditEmailActivity.class);
                intent.putExtra("email", emailView.getText().toString());
                startActivity(intent);
                break;
            case R.id.cl_my_mobile:
                EventBus.getDefault().post(new MessageUpdatePersonEvent(null));
                if (StringUtil.isValid(DKUserManager.getUserInfo().getPhone())) {
                    startActivity(new Intent(this, ShowMobileActivity.class));
                } else {
                    ARouter.getInstance().build(LoginProtocol.UNBIND_BIND_PHONE).navigation();
                }
                break;
            case R.id.cl_update_password:
                EventBus.getDefault().post(new MessageUpdatePersonEvent(null));
                startActivity(new Intent(this, ModifyPasswdActivity.class));
                break;
            case R.id.iv_avatar:
                AliUIDisplayer aliUIDisplayer = new AliUIDisplayer(avatarView, this, uploadListener);
                uploadHelper = new AliUploadHelper(this, aliUIDisplayer);
                changeAvatar.checkPermission(new CameraHandlerTow(this));
                break;
        }
    }
}
